package com.dempsey.gateway.service;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.dempsey.api.model.LoginUser;
import com.dempsey.common.security.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 3. 权限验证，是否放行
 *
 * @author zhe.xiao
 * @date 2021-04-15 11:12
 * @description
 */
@Component
public class ScAuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {

    private final static Log log = LogFactory.get();

    @Autowired
    private TokenService tokenService;

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext authorizationContext) {
        return authentication.map(auth -> {
            log.info("3. 权限验证，是否放行");
            LoginUser loginUser = (LoginUser) auth.getPrincipal();
            if (null != loginUser) {
                log.info("刷新token时间，loginUser：{}", loginUser);
                tokenService.refreshToken(loginUser);
                SecurityContextHolder.getContext().setAuthentication(auth);
                return new AuthorizationDecision(true);
            }
            return new AuthorizationDecision(false);
        }).defaultIfEmpty(new AuthorizationDecision(false));
    }

}